<?php

namespace app\admin\controller\slider;
require_once APP_PATH . '/api/common.php';

use app\common\controller\Backend;
use app\common\library\ImageProcessor;
use fast\Tree;
use phpseclib3\Crypt\EC\Formats\Keys\JWK;
use think\Db;
use think\exception\ValidateException;
use think\exception\PDOException;
use Exception;


/**
 * 
 *
 * @icon fa fa-file
 */
class Slider extends Backend
{

    /**
     * Slider模型对象
     */
    protected $model = null;
    protected $noNeedRight = ["lists"];
    protected $noNeedLogin = [];


    public function _initialize()
    {
        parent::_initialize();
        $this->shopid = false;
        $this->model = model('Slider');
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            // 获取城市和学校过滤参数
            $city_id = $this->request->get("city_id");
            $school_id = $this->request->get("school_id");
            $type = $this->request->get("type"); // 添加类型参数

            $total = $this->model
                ->where($where)->where("status", "=", 1);

            // 添加类型过滤
            if (!empty($type)) {
                if($type=="teaching-point"){
                    $total = $total->where("number", "=", 42);
                }
                else if($type=="city-home"){
                    $total = $total->where("number", "=", 41);
                }
                else if($type=="school-home"){
                    $total = $total->where("number", "=", 44);
                }
                else if($type=="class-home"){
                    $total = $total->where("number", "=", 43);
                }
                else if($type=="community-subject"){
                    $total = $total->where("number", "=", 48);
                }
                else if($type=="order"){
                    $total = $total->where("number", "in", [45,46,47]);
                }
            }

            // 添加城市过滤
            if (!empty($city_id)) {
                $total = $total->where("city_id", "=", $city_id);
            } else if (isset($_SESSION['think']['admin']['group_id']) && ($_SESSION['think']['admin']['group_id'] == 2||$_SESSION['think']['admin']['group_id'] == 3)) {
                $total = $total->where("city_id", "=", $_SESSION['think']['admin']['city_id']);
            }

            // 添加学校过滤
            if (!empty($school_id)) {
                $total = $total->where("school_id", "=", $school_id);
            }

            $total = $total->count();

            $list = $this->model
                ->where($where)->where("status", "=", 1);

            // 添加类型过滤
            if (!empty($type)) {
                if ($type == "city-home") {
                    $list = $list->where("number", "=", 41);
                } else if ($type == "teaching-point") {
                    $list = $list->where("number", "=", 42);
                } else if ($type == "school-home") {
                    $list = $list->where("number", "=", 44);
                } else if ($type == "class-home") {
                    $list = $list->where("number", "=", 45);
                } else if ($type == "community-subject") {
                    $list = $list->where("number", "=", 48);
                } else if ($type == "teaching-point_sq") {
                    $list = $list->where("number", "=", 49);
                } else if ($type == "order") {
                    $list = $list->where("number", "in", [46, 47]);
                }
            }

                    // 添加城市过滤
            if (!empty($city_id)) {
                $list = $list->where("city_id", "=", $city_id);
            } else if (isset($_SESSION['think']['admin']['group_id'])  && ($_SESSION['think']['admin']['group_id'] == 2||$_SESSION['think']['admin']['group_id'] == 3)) {
                $list = $list->where("city_id", "=", $_SESSION['think']['admin']['city_id']);
            }

            // 添加学校过滤
            if (!empty($school_id)) {
                $list = $list->where("school_id", "=", $school_id);
            }

            $list = $list->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            foreach ($list as $row) {
                $row->getRelation('type');
            }
            $list = collection($list)->toArray();
            for ($i = 0; $i < count($list); $i++) {
                $list[$i]['city_id'] = model("Cityarea")->getCity_idTextAttr($list[$i]['city_id'], $list[$i]);
                $list[$i]['school_id'] = model("School")->getSchool_idTextAttr($list[$i]['school_id'], $list[$i]);
                $list[$i]['number'] = model("Category")->where("type", "number")->where("id", $list[$i]['number'])->value("name");
                // 图片预览
                if ($list[$i]['image']) {
                    $list[$i]['image'] = json_decode($list[$i]['image'], true);
                    $list[$i]['image'] = $list[$i]['image'];
                    foreach ($list[$i]['image'] as $key => $value) {
                        $list[$i]['image'][$key]['src'] = getImg($list[$i]['image'][$key]['src'], 750, 422);
                    }
                }
                $list[$i]['title_image'] = getImg($list[$i]['title_image'], 200, 200);
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                if(isset($params['city_id'])){
                    $city_id=$params['city_id'];
                }
                if(isset($params['school_id'])){
                    $school_id=$params['school_id'];
                }
                // 自动插入session中的城市和学校ID
                if (isset($_SESSION['think']['admin']['city_id']) && !isset($params['city_id'])) {
                    $params['city_id'] = $_SESSION['think']['admin']['city_id'];
                }
                if (isset($_SESSION['think']['admin']['school_id']) && !isset($params['school_id'])) {
                    $params['school_id'] = $_SESSION['think']['admin']['school_id'];
                }

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;

                // 处理图片数组，下载和裁剪外部图片
                if (isset($_POST['images']) && is_array($_POST['images'])) {
                    $processedImages = $this->processImages($_POST['images'], $params);
                    $params['image'] = json_encode($processedImages, JSON_UNESCAPED_UNICODE);
                } else {
                    $params['image'] = json_encode($_POST['images'] ?? [], JSON_UNESCAPED_UNICODE);
                }
                $params['title_image'] = $params['title_image'] ?? "";
                // 处理标题图片
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\", "/", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    unset( $params['city_id']);
                    unset( $params['school_id']);
                    if(isset($city_id)){
                        $params['city_id']=$city_id;
                    }
                    if(isset($school_id)){
                        $params['school_id']=$school_id;
                    }
                    // 获取新插入的ID
                    $newId = $this->model->id;

                    // 处理关联表数据更新（参考edit方法）
                    $image = $this->model->getimages(json_decode($params['image'], true));
                    $imageField = $this->model->getimagesfield(json_decode($params['image'], true));

                    if (isset($params['ocation_id']) && $params['ocation_id'] > 0) {
                        $data = array(
                            'slider_id' => $newId,
                            'header_image' => $image[0] ?? "",
                            'image' => $imageField,
                            'cover'=>$params['title_image']??""
                        );
                        model("Ocation")->where('id', $params['ocation_id'])->update($data);
                    }
                    if (isset($params['school_id']) && $params['school_id'] > 0) {
                        $data = array(
                            'slider_id' => $newId,
                            'thumbnail' => $image[0] ?? "",
                            'image' => $imageField,
                            'header_image' => $image[0] ?? "",
                            'cover'=>$params['title_image']??""
                        );
                        model("School")->where('id', $params['school_id'])->update($data);
                    }
                    if(isset($params['classes_id'])&&$params['classes_id']>0){
                        $data=array(
                            'slider_id'=>$newId,
                            'image'=>$imageField,
                            'header_image'=>$image[0]??"",
                            'cover'=>$params['title_image']??"",
                        );
                        model("Classes")->where('id',$params['classes_id'])->update($data);
                    }
                    if (isset($params['communityCourse_id']) && $params['communityCourse_id'] > 0) {
                        $data = array(
                            'slider_id' => $newId,
                            'image' => $imageField,
                            'header_image' => $image[0] ?? "",
                            'cover'=>$params['title_image']??"",
                        );
                        db::name("fa_community_course_config")->where('id', $params['communityCourse_id'])->update($data);
                    }

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                if(isset($params['city_id'])){
                    $city_id=$params['city_id'];
                }
                if(isset($params['school_id'])){
                    $school_id=$params['school_id'];
                }
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                // 自动插入session中的城市和学校ID（仅在字段为空时）
                if (isset($_SESSION['think']['admin']['city_id']) && (empty($row['city_id']) || !isset($params['city_id']))) {
                    $params['city_id'] = $_SESSION['think']['admin']['city_id'];
                }
                // 自动插入session中的城市和学校ID（仅在字段为空时）
                if (isset($_SESSION['think']['admin']['city_id']) && (empty($row['city_id']) || !isset($params['city_id']))) {
                    $params['city_id'] = $_SESSION['think']['admin']['city_id'];
                }
                if (isset($_SESSION['think']['admin']['school_id']) && (empty($row['school_id']) || !isset($params['school_id']))) {
                    $params['school_id'] = $_SESSION['think']['admin']['school_id'];
                }
                // 处理图片数组，下载和裁剪外部图片
                if (isset($_POST['images']) && is_array($_POST['images'])) {
                    $processedImages = $this->processImages($_POST['images'], $params);
                    $params['image'] = json_encode($processedImages, JSON_UNESCAPED_UNICODE);
                } else {
                    $params['image'] = json_encode($_POST['images'] ?? [], JSON_UNESCAPED_UNICODE);
                }
                $params['title_image'] = $params['title_image'] ?? "";

                $result = false;
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\", "/", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    unset( $params['city_id']);
                    unset( $params['school_id']);
                    if(isset($city_id)){
                        $params['city_id']=$city_id;
                    }
                    if(isset($school_id)){
                        $params['school_id']=$school_id;
                    }
                    $image=$this->model->getimages(json_decode($params['image'],true));
                    $imageField=$this->model->getimagesfield(json_decode($params['image'],true));
                    if(isset($params['ocation_id'])&&$params['ocation_id']>0){
                        $data=array(
                            'slider_id'=>$ids,
                            'header_image'=>$image[0]??"",
                            'image'=>$imageField,
                            'cover'=>$params['title_image']??""
                        );
                        if($data["image"]=="[]"){
                            unset($data['image']);
                        }
                        if($data["header_image"]=="[]"){
                            unset($data['header_image']);
                        }
                        if($data["cover"]=="[]"){
                            unset($data['cover']);
                        }
                        model("Ocation")->where('id',$params['ocation_id'])->update($data);
                        $ocation_parent=model("Ocation")->where('pid',$params['ocation_id'])->field("image,header_image,cover")->find();
                        if($ocation_parent&&(!$ocation_parent["image"]||!$ocation_parent["header_image"]||!$ocation_parent["cover"])){
                            if($data["image"]=="[]"){
                                unset($data['image']);
                            }
                            if($data["header_image"]=="[]"){
                                unset($data['header_image']);
                            }
                            if($data["cover"]=="[]"){
                                unset($data['cover']);
                            }
                            model("Ocation")->where('pid',$params['ocation_id'])->update($data);
                        }
                    }
                    if(isset($params['school_id'])&&$params['school_id']>0){
                        $data=array(
                            'slider_id'=>$ids,
                            'thumbnail'=>$image[0]??"",
                            'image'=>$imageField,
                            'header_image'=>$image[0]??"",
                            'cover'=>$params['title_image']??""
                        );
                        model("School")->where('id',$params['school_id'])->update($data);
                    }
                    if(isset($params['classes_id'])&&$params['classes_id']>0){
                        $data=array(
                            'slider_id'=>$ids,
                            'image'=>$imageField,
                            'header_image'=>$image[0]??"",
                            'cover'=>$params['title_image']??"",
                        );
                        model("Classes")->where('id',$params['classes_id'])->update($data);
                    }
                    if(isset($params['communityCourse_id'])&&$params['communityCourse_id']>0){
                        $data=array(
                            'slider_id'=>$ids,
                            'image'=>$imageField,
                            'header_image'=>$image[0]??"",
                            'cover'=>$params['title_image']??"",
                        );
                        db::name("fa_community_course_config")->where('id',$params['communityCourse_id'])->update($data);
                    }
                } catch (ValidateException $e) {
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function view($ids = NULL)
    {
        $row = $this->model->getRow($ids);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function lists($ids = NULL)
    {
        $where = "";
        $page = 1;
        $pagesize = 50;
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                $keyField = $this->request->request("keyField");
                $keyValue = $this->request->request("keyValue");
                $page = $this->request->request("pageNumber");
                $page = ($page == null) ? 1 : $page;
                $pagesize = $this->request->request("pageSize");
                $pagesize = ($pagesize == null) ? 10 : $pagesize;
                if ($keyValue != "") {
                    $nn = preg_split("/\,/", $keyValue);
                    $where = "where 1=0";
                    for ($i = 0; $i < count($nn); $i++) {
                        $where .= " or $keyField='{$nn[$i]}'";
                    }
                }
            }
        }
        $sql = "select id,number name from dev002_gxyusheng.fa_slider $where limit " . (($page - 1) * $pagesize) . ",$pagesize";
        $list = db()->query($sql);

        //$tree = Tree::instance();
        //$tree->init($list, 'pid');
        //if(isset($keyValue)&&$keyValue!=""){
        //}else{
        //    $list=$tree->getTreeList($tree->getTreeArray(0), 'name');
        //    //array_unshift($list,array("name"=>"无父级","pid"=>0,"weigh"=>9999));
        //}

        $total = db()->query("select count(1) as c from  dev002_gxyusheng.fa_slider $where")[0];
        echo json_encode(array("list" => $list, "total" => $total['c']));
        exit;
    }

    /**
     * 处理图片数组，下载和裁剪外部图片
     * @param array $images 图片数组
     * @param array $params 参数数组（包含image_width和image_height）
     * @return array 处理后的图片数组
     */
    private function processImages($images, $params)
    {
        $processedImages = [];

        // 获取目标尺寸
        $targetWidth = isset($params['image_width']) ? intval($params['image_width']) : 800;
        $targetHeight = isset($params['image_height']) ? intval($params['image_height']) : 600;

        foreach ($images as $key => $image) {
            if (is_array($image) && isset($image['src'])) {
                $imageUrl = $image['src'];

                // 检查是否为外部图片（以http开头）
                if (strpos($imageUrl, 'http://') === 0 || strpos($imageUrl, 'https://') === 0) {
                    // 生成本地文件路径
                    $localPath = $this->generateLocalPath($imageUrl);

                    try {
                        // 下载并裁剪外部图片
                        $success = $this->downloadAndResizeImage($imageUrl, $localPath, $targetWidth, $targetHeight);

                        if ($success) {
                            // 更新图片地址为本地路径
                            $image['src'] = $localPath;
                            \think\Log::info("外部图片处理成功: {$imageUrl} -> {$localPath}");
                        } else {
                            \think\Log::error("外部图片处理失败: {$imageUrl}");
                            // 处理失败时保持原URL
                        }
                    } catch (Exception $e) {
                        \think\Log::error("外部图片处理异常: {$imageUrl}, 错误: " . $e->getMessage());
                        // 异常时保持原URL
                    }
                }

                $processedImages[$key] = $image;
            } else {
                // 非标准格式的图片数据，直接保留
                $processedImages[$key] = $image;
            }
        }
        if(count($processedImages)==1&&$processedImages[1]["src"]==""||count($processedImages)==0){
            return array();
        }
        return $processedImages;
    }

    /**
     * 根据外部图片URL生成本地存储路径
     * @param string $externalUrl 外部图片URL
     * @return string 本地相对路径
     */
    private function generateLocalPath($externalUrl)
    {
        // 获取文件扩展名
        $pathInfo = pathinfo(parse_url($externalUrl, PHP_URL_PATH));
        $extension = isset($pathInfo['extension']) ? $pathInfo['extension'] : 'jpg';

        // 生成基于URL的唯一文件名
        $filename = md5($externalUrl) . '.' . $extension;

        // 按日期分目录存储
        $dateDir = date('Ymd');
        $relativePath = "/uploads/{$dateDir}/{$filename}";

        return $relativePath;
    }

    /**
     * 下载并裁剪外部图片
     * @param string $externalUrl 外部图片URL
     * @param string $localPath 本地保存路径（相对路径）
     * @param int $width 目标宽度
     * @param int $height 目标高度
     * @return bool
     */
    private function downloadAndResizeImage($externalUrl, $localPath, $width, $height)
    {
        try {
            // 构建完整的本地文件路径
            $fullLocalPath = ROOT_PATH . 'public' . $localPath;

            // 确保目录存在
            $localDir = dirname($fullLocalPath);
            if (!is_dir($localDir)) {
                mkdir($localDir, 0755, true);
            }

            // 下载远程图片，支持HTTPS
            $context = stream_context_create([
                'http' => [
                    'timeout' => 30,  // 30秒超时
                    'user_agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
                    'follow_location' => true,
                    'max_redirects' => 5,
                ],
                'ssl' => [
                    'verify_peer' => false,
                    'verify_peer_name' => false,
                    'allow_self_signed' => true,
                ]
            ]);

            $imageContent = file_get_contents($externalUrl, false, $context);
            if ($imageContent === false) {
                return false;
            }

            // 保存到临时文件
            $tempFile = sys_get_temp_dir() . '/' . uniqid('remote_img_') . '.tmp';
            if (file_put_contents($tempFile, $imageContent) === false) {
                return false;
            }

            // 获取图片信息
            $imageInfo = getimagesize($tempFile);
            if (!$imageInfo) {
                unlink($tempFile);
                return false;
            }

            $originalWidth = $imageInfo[0];
            $originalHeight = $imageInfo[1];
            $imageType = $imageInfo[2];

            // 如果原图尺寸已经符合要求，直接复制
            if ($originalWidth == $width && $originalHeight == $height) {
                $result = copy($tempFile, $fullLocalPath);
                unlink($tempFile);
                return $result;
            }

            // 创建原图资源
            switch ($imageType) {
                case IMAGETYPE_JPEG:
                    $sourceImage = imagecreatefromjpeg($tempFile);
                    break;
                case IMAGETYPE_PNG:
                    $sourceImage = imagecreatefrompng($tempFile);
                    break;
                case IMAGETYPE_GIF:
                    $sourceImage = imagecreatefromgif($tempFile);
                    break;
                case IMAGETYPE_BMP:
                    $sourceImage = imagecreatefrombmp($tempFile);
                    break;
                case IMAGETYPE_WEBP:
                    $sourceImage = imagecreatefromwebp($tempFile);
                    break;
                default:
                    unlink($tempFile);
                    return false;
            }

            if (!$sourceImage) {
                unlink($tempFile);
                return false;
            }

            // 创建目标图片资源
            $targetImage = imagecreatetruecolor($width, $height);

            // 保持PNG和GIF的透明度
            if ($imageType == IMAGETYPE_PNG || $imageType == IMAGETYPE_GIF) {
                imagealphablending($targetImage, false);
                imagesavealpha($targetImage, true);
                $transparent = imagecolorallocatealpha($targetImage, 255, 255, 255, 127);
                imagefilledrectangle($targetImage, 0, 0, $width, $height, $transparent);
            }

            // 计算原图和目标图的宽高比
            $originalRatio = $originalWidth / $originalHeight;
            $targetRatio = $width / $height;

            // 计算缩放比例
            $scaleX = $width / $originalWidth;
            $scaleY = $height / $originalHeight;

            // 使用较大的缩放比例，确保完全填充目标尺寸
            $scale = max($scaleX, $scaleY);

            $newWidth = intval($originalWidth * $scale);
            $newHeight = intval($originalHeight * $scale);

            // 创建临时缩放图片
            $tempImage = imagecreatetruecolor($newWidth, $newHeight);

            // 保持透明度
            if ($imageType == IMAGETYPE_PNG || $imageType == IMAGETYPE_GIF) {
                imagealphablending($tempImage, false);
                imagesavealpha($tempImage, true);
                $transparent = imagecolorallocatealpha($tempImage, 255, 255, 255, 127);
                imagefilledrectangle($tempImage, 0, 0, $newWidth, $newHeight, $transparent);
            }

            // 先将原图缩放到临时图片
            imagecopyresampled(
                $tempImage,
                $sourceImage,
                0,
                0,
                0,
                0,
                $newWidth,
                $newHeight,
                $originalWidth,
                $originalHeight
            );

            // 计算裁剪位置
            if ($originalRatio > $targetRatio) {
                // 宽图片：宽度填满，高度从底部裁剪
                $cropX = 0;  // 宽度不裁剪
                $cropY = max(0, $newHeight - $height);  // 高度从底部裁剪，保留上半部分
            } else {
                // 高图片：从上下和左右的中间裁剪，保留真正中间的部分
                $cropX = intval(($newWidth - $width) / 2);   // 宽度居中裁剪
                $cropY = intval(($newHeight - $height) / 2); // 高度居中裁剪
            }

            // 从临时图片裁剪到目标图片
            imagecopyresampled(
                $targetImage,
                $tempImage,
                0,
                0,
                $cropX,
                $cropY,
                $width,
                $height,
                $width,
                $height
            );

            // 释放临时图片内存
            imagedestroy($tempImage);

            // 保存图片
            switch ($imageType) {
                case IMAGETYPE_JPEG:
                    $result = imagejpeg($targetImage, $fullLocalPath, 90);
                    break;
                case IMAGETYPE_PNG:
                    $result = imagepng($targetImage, $fullLocalPath, 9);
                    break;
                case IMAGETYPE_GIF:
                    $result = imagegif($targetImage, $fullLocalPath);
                    break;
                case IMAGETYPE_BMP:
                    $result = imagebmp($targetImage, $fullLocalPath);
                    break;
                case IMAGETYPE_WEBP:
                    $result = imagewebp($targetImage, $fullLocalPath, 90);
                    break;
                default:
                    $result = false;
            }

            // 释放内存
            imagedestroy($sourceImage);
            imagedestroy($targetImage);

            // 清理临时文件
            unlink($tempFile);

            return $result;
        } catch (Exception $e) {
            // 清理临时文件
            if (isset($tempFile) && file_exists($tempFile)) {
                unlink($tempFile);
            }

            \think\Log::error('外部图片下载和裁剪失败: ' . $e->getMessage());
            return false;
        }
    }
}
